package com.example.jiancaiwang.utils;

import android.os.Handler;

import com.example.jiancaiwang.callback.MyOkhttpCallBack;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/***
 * 单例模式---》保证client对象只有一个---》节省资源
 */
public class OkhttpUtils {
    private OkHttpClient okHttpClient;
    private Handler handler = new Handler();


    private OkhttpUtils(){//构造执行一次
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60*1000, TimeUnit.MILLISECONDS)
                .writeTimeout(60*1000, TimeUnit.MILLISECONDS)
                .connectTimeout(60*1000, TimeUnit.MILLISECONDS)
                .build();
    }
    private static OkhttpUtils okhttpUtils = new OkhttpUtils();
    public static OkhttpUtils getInstance(){
        if(okhttpUtils == null){
            okhttpUtils = new OkhttpUtils();
        }
        return okhttpUtils;
    }



    public void doGet(String url, final MyOkhttpCallBack myOkhttpCallBack){
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //主线程
                        if(myOkhttpCallBack != null){
                            myOkhttpCallBack.onError(message);
                        }

                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //主线程
                        if(myOkhttpCallBack != null){
                            myOkhttpCallBack.onOk(string);
                        }
                    }
                });
            }
        });


    }

}
